package com.andryyu.learn.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import com.andryu.base.entity.LearnHeaderEntity
import com.andryu.learn.R

class LearnHeaderAdapter(private val categoryList:MutableList<LearnHeaderEntity<*>>) :
    RecyclerView.Adapter<LearnHeaderAdapter.ViewHolder>(){

    private var mSelectPosition: Int = 0
    private var mListener: ((entity: LearnHeaderEntity<*>) -> Unit?)? = null

    fun setOnItemClick(listener:(entity: LearnHeaderEntity<*>) -> Unit){
        mListener = listener
    }

    fun updateItems(mutableList: MutableList<LearnHeaderEntity<*>>){
        categoryList.clear()
        categoryList.addAll(mutableList)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_home_content, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int = categoryList.size

    override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val entity = categoryList[position]
        holder.run {
            mItemName.text = entity.name
            itemView.setOnClickListener {
                mListener?.invoke(entity)
                if (position != mSelectPosition){
                    notifyItemChanged(mSelectPosition)
                    mSelectPosition = position
                }
                notifyItemChanged(position)
            }

            mItemName.isSelected = (position == mSelectPosition)
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mItemName: AppCompatTextView = itemView.findViewById(R.id.tv_home_item)
    }
}